package com.modern.js.controller;

import com.modern.js.entity.Employee;
import com.modern.js.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService iEmployeeService;

    @PostMapping("/doLogin")
    @ResponseBody
    public boolean doLogin(@RequestBody Map<String, String> map, HttpSession session){
        System.out.println("你好");
        System.out.println(map);
        System.out.println("fgf:"+map.get("empName"));
        //拿到当前主体对象，用作验证   （从安全工具类中拿到subject）
        Subject subject = SecurityUtils.getSubject();
        //将用户名和密码包装到token中
        UsernamePasswordToken token = new UsernamePasswordToken(map.get("empName"),map.get("pwd"));
        //通过捕获异常来判断用户是否是否可以登录
        try{
            subject.login(token);
            System.out.println("这是获取的值："+SecurityUtils.getSubject().getPrincipal());
            String name = (String) SecurityUtils.getSubject().getPrincipal();
            Employee employee = iEmployeeService.selectByName(name);
            session.setAttribute("employee",employee);
            System.out.println("登录成功！");
        }catch (UnknownAccountException uae){
            System.out.println("用户名不存在");
            return false;
        }catch (IncorrectCredentialsException ice){
            System.out.println("密码错误");
            return false;
        }
        return true;
    }

}
